package com.example.homework.repositories

import android.content.Context
import android.content.SharedPreferences
import androidx.appcompat.app.AppCompatActivity.MODE_APPEND
import androidx.appcompat.app.AppCompatActivity.MODE_PRIVATE
import java.io.File
import java.io.FileInputStream
import java.io.FileNotFoundException
import java.io.FileOutputStream
import java.io.IOException

class DataRepository(val context: Context) {
    companion object {
        const val DATA_SHARED_PREFERENCES_NAME = "UserData"
        const val USER_VALUE_NAME = "UserInput"
        const val FILE_NAME = "UserFile.txt"
    }

    private val sharedPreference: SharedPreferences =
        context.getSharedPreferences(DATA_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE)
    private val sharedPreferenceEditor: SharedPreferences.Editor = sharedPreference.edit()
    private var localVal: String? = null

    private fun getDataFromSharedPreference(): String? {
        localVal = sharedPreference.getString(USER_VALUE_NAME, null)
        return localVal
    }

    private fun getDataFromLocalVariable(): String? {
        return localVal
    }

    private fun getDataFromFile(): String {
        var fis: FileInputStream? = null
        return try {
            fis = context.openFileInput(FILE_NAME)
            val bytes: ByteArray = ByteArray(fis.available())
            fis.read(bytes)
            String(bytes)
        }
        catch (ex: FileNotFoundException) {
            ""
        } finally {
            fis?.close()
        }
    }

    fun writeDataToFile(input: String) {
        var fos: FileOutputStream? = null
        try {
            fos = context.openFileOutput(FILE_NAME, MODE_APPEND)
            fos.write(input.toByteArray())
        } catch (ex: IOException) {
            println(ex.message)
        } finally {
            fos?.close()
        }
    }

    fun clearDataFromFile() {
        try {
            context.deleteFile(FILE_NAME)
        } catch (ex: IOException) {
            println(ex.message)
        }
    }

    fun saveText(text: String) {
        sharedPreferenceEditor.putString(USER_VALUE_NAME, text)
        sharedPreferenceEditor.apply()
    }

    fun clearText() {
        sharedPreferenceEditor.clear()
        sharedPreferenceEditor.apply()
        getDataFromSharedPreference()
    }

    fun getTextFromCache(): String = when {
        getDataFromLocalVariable() != null -> getDataFromLocalVariable()!!
        getDataFromSharedPreference() != null -> getDataFromSharedPreference()!!
        else -> "No data was found in cache"
    }

    fun getTextFromFile(): String = when {
        getDataFromFile() != "" -> getDataFromFile()
        else -> "No data was found in file"
    }
}